<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/19  14:05
// +----------------------------------------------------------------------
namespace Wechat\Controller;
use Think\Controller;

//书
Class BookController extends BaseController {
    function index() {
        $this->redirect("blist");
    }

    //搜索图书 根据keyword或者type
    function blist() {
        $this->display();
    }

    //搜索图书-ajax用 根据keyword或者type
    function get_blist() {
        $keyword = I("get.keyword");
        $type = I("get.type");
        $index = I("get.i");    //起始记录
        $num = I("get.num");    //条数
        $mapstr='is_del="0"';
        if ($keyword != "") {
            $mapstr.=' AND (sm LIKE "%'.$keyword.'%" or zyz LIKE "%'.$keyword.'%" or tm LIKE "%'.$keyword.'%" )';
        }
        if ($type != "") {
            $maptype='type_id in ('.$type.')';
            $Book_type = M("View_book_has_type");
            $t = $Book_type->where($maptype)->field("book_id")->select();
            $t_str = "";
            foreach ($t as $k => $v) {
                $t_str .= '"'.$v['book_id'] . '"'. ",";
            }
            $t_str = substr($t_str, 0, strlen($t_str) - 1);
            unset($map);
            $mapstr.=' AND a.book_id in ('.$t_str.')';
        }
        $Book = M("Book");
        $d = $Book->alias('a')
            ->where($mapstr)
            ->join("view_book_rented_num b ON a.book_id=b.book_id", "LEFT")
            ->join("view_book_apprise_num c ON a.book_id=c.book_id", "LEFT")
            ->order("sort desc,book_id desc")
            ->limit($index . "," . $num)
            ->field("a.book_id,a.sm,a.dj,a.b_rec,a.b_logo,b.rented_num,c.apprise_num")
            ->select();
        if (sizeof($d) == 0) {
            echo 0;
            return;
        }
        foreach ($d as $k => $v) {
            $d[$k]['dj'] = number_format(round($d[$k]['dj'], 2), 2);
            $d[$k]['detail_url'] = U("Book/detail", "id=" . $d[$k]['book_id']);
            if ($d[$k]['rented_num'] == NULL) {
                $d[$k]['rented_num'] = 0;
            }
            if ($d[$k]['apprise_num'] == NULL) {
                $d[$k]['apprise_num'] = 0;
            }
        }
        echo json_encode($d);
    }

    //首页-推荐书籍-ajax用
    function getbook_recommend() {
        $Book = M("Book");
        $index = I("get.i");
        $num = I("get.num");
        $d = $Book->alias('a')->where("is_del=0")->join("view_book_rented_num b ON a.book_id=b.book_id", "LEFT")->join("view_book_apprise_num c ON a.book_id=c.book_id", "LEFT")->order("sort desc")->limit($index . "," . $num)->field("a.book_id,a.sm,a.dj,a.b_rec,a.b_logo,b.rented_num,c.apprise_num")->select();
        if (sizeof($d) == 0) {
            echo 0;
            return;
        }
        foreach ($d as $k => $v) {
            $d[$k]['dj'] = number_format(round($d[$k]['dj'], 2), 2);
            $d[$k]['detail_url'] = U("Book/detail", "id=" . $d[$k]['book_id']);
            if ($d[$k]['rented_num'] == NULL) {
                $d[$k]['rented_num'] = 0;
            }
            if ($d[$k]['apprise_num'] == NULL) {
                $d[$k]['apprise_num'] = 0;
            }
        }
        echo json_encode($d);
    }

    //搜索页
    function kind() {
        $Type = M("Book_type");
        $up = $Type->where("pid='0'")->select();
        $type = $Type->where("pid!='0'")->select();
        $this->assign("up", $up);
        $this->assign("type", $type);
        $this->display();
    }

    /**
     *图书详情
     */
    function detail() {
        $book_id = I("get.id");
        $user_id = session("user_id");
        if (!is_numeric($book_id)) {
            return;
        }
        $Book = M("Book");
        //当前图书信息
        $d = $Book->where("book_id=$book_id")->field("book_id,sm,dj,zyz,press,b_rec,bdetail,kb,b_logo")->find();
        if (!$d) {
            return;
        }
        $favbook = M("Favorite_book");
        $count = $favbook->where("book_id=$book_id AND user_id=" . session("user_id"))->count();
        $d["is_fav"] = $count;
        //相关推荐的书
//        $d_rec = $Book->order("sort desc")->limit("0,8")->field("book_id,sm,b_logo")->select();
        $d_rec = $Book->order("rand()")->fetchSql(false)->limit("0,8")->field("book_id,sm,b_logo")->select();
//        var_dump($d_rec);exit;
        //当前图书的订单评论
        $Apprise = M("view_apprise_has_user");
        $d_apr = $Apprise->where("book_id=$book_id AND is_show='1'")->limit("0,5")->select();
        //当前书包数量
        $Cart = M("View_cart_book");
        $d['wrent_num'] = $Cart->where("cart_type=1 AND user_id=$user_id")->count(); //书包里的数量
        $d['wbuy_num'] = $Cart->where("cart_type=0 AND user_id=$user_id")->count();  //购物车里的数量
        ////////////////////////////
        $this->assign("d", $d);
        $this->assign("d_rec", $d_rec);
        $this->assign("d_apr", $d_apr);
        $this->display();
    }

    //是否已借阅过或购买过
    function is_rentorbuy() {
        //返回 1：已有借阅记录；0：未曾借阅过
        $book_id = I("post.id");
        $type = I("post.type");
        $user_id = session("user_id");
        $Order_book = M("Order_has_book");
        //当前用户订单
        $Order = M("Order_book");
        $do = $Order->where("user_id=$user_id")->select();
        $orderlist = array();
        foreach ($do as $k => $v) {
            array_push($orderlist, $v["order_id"]);
        }
        if (sizeof($orderlist) == 0) {
            $count1 = 0;
        } else {
            $map["type"] = $type;
            $map["book_id"] = $book_id;
            $map["order_id"] = array("in", $orderlist);
            $count1 = $Order_book->where($map)->count(); //订单图书
        }
        $Cart = M("Cart");
        $count2 = $Cart->where("type=$type AND book_id=$book_id AND user_id=$user_id")->count();
        $count = $count1 + $count2;
        echo $count;
    }

    /**
     *加入书包-ajax用，
     * type  1:加入书包;2:加入购物车
     * id    图书id
     * 返回  1借阅成功，0为已借阅，-1为借阅失败(书籍借阅库存不足)
     *
     */
    function joincart() {
        $type = I("get.type");
        if (!is_numeric($type)) {
            return;
        }
        $book_id = I("get.id");
        $user_id = session("user_id");
        $Cart = M("Cart");
        $count = $Cart->where("user_id=$user_id AND book_id=$book_id AND type=$type")->count();
        if ($count > 0) {
            $Cart->startTrans();
            $Cart->where("user_id=$user_id AND book_id=$book_id AND type=$type")->setInc("quantity", 1);
            $data["update_time"] = date("Y-m-d h:i:s", time());
            $Cart->where("user_id=$user_id AND book_id=$book_id AND type=$type")->save($data);
            $Cart->commit();
            echo 1;
            return;
        }
        $data['user_id'] = $user_id;
        $data['book_id'] = $book_id;
        $data['quantity'] = 1;
        $data['type'] = $type;
        $data['update_time'] = date("Y-m-d h:i:s", time());
        $Cart->startTrans();
        $count1 = $Cart->add($data);
        if ($count1) {
            // 如果主键是自动增长型 成功后返回值就是最新插入的值
            $Cart->commit();
        }
        echo 1;
    }
    //加入收藏
    //返回 1-成功，0-失败，可能为已收藏或已取消收藏，
    function join_fav() {
        $book_id = I("get.id");
        $user_id = session("user_id");
        if (!is_numeric($book_id)) {
            echo 0;
            return;
        }
        $fav_book = M("favorite_book");
        $map['book_id'] = $book_id;
        $map['user_id'] = $user_id;
        $count = $fav_book->where($map)->count();
        if ($count > 0) {
            echo 0;
            return;
        }
        $count1 = $fav_book->data($map)->add();
        if ($count1) {
            echo 1;
        } else {
            echo 0;
        }
    }

    //取消收藏
    function cancel_fav() {
        $book_id = I("get.id");
        $user_id = session("user_id");
        if (!is_numeric($book_id)) {
            echo 0;
            return;
        }
        $fav_book = M("favorite_book");
        $map['book_id'] = $book_id;
        $map['user_id'] = $user_id;
        $count = $fav_book->where($map)->count();
        if ($count == 0) {
            echo 0;
            return;
        }
        $fav_book->startTrans();
        $fav_book->where($map)->delete();
        $count1 = $fav_book->where($map)->count();
        if ($count1 == 0) {
            $fav_book->commit();
            echo 1;
        } else {
            $fav_book->rollback();
            echo 0;
        }
    }
}